<template>
  <div class="map-container" style="margin-left: 10px;">
    <div id="grid-map-container"></div>
    <div class="info" v-if="operationType != 3">
      <el-input id="tipinput" v-model="mapSearch.key" class="input-with tipinput" placeholder="" clearable @keyup.native.enter="handleMapSearch">
        <el-button slot="append" size="small" type="primary" icon="el-icon-search" @click="handleMapSearch"></el-button>
      </el-input>
    </div>
    <div class="input-card" style="width: 120px; position: absolute;" v-if="operationType != 3 && showPolyEditor">
      <el-button type="primary" plain @click="polyEditorOpen" style="margin-bottom: 5px">开始编辑</el-button>
      <el-button type="primary" plain @click="polyEditorClose" style="margin-left: 0;">结束编辑</el-button>
    </div>
  </div>
</template>

<script>
import AMap from 'AMap';
import $ from 'jquery'

export default {
  name: 'RangeMap',
  props: {
    pointstr: {
      type: String
    },
    operationType: {
      type: Number,
      default: 1 //操作类型，1=新增，2=编辑，3=查看
    },
  },
  data() {
    return {
      //operationType: 1,  //操作类型，1=新增，2=编辑，3=查看
      center: [process.env.VUE_APP_LONGITUDE_DEFAULT, process.env.VUE_APP_LATITUDE_DEFAULT],
      lng: 0,
      lat: 0,
      zoom: 16,
      // 线条颜色
      strokeColor: '#176ffc',
      // 线条透明度
      strokeOpacity: 0.6,
      // 线条宽度
      strokeWeight: 1,
      // 填充颜色
      fillColor: '#1791fc',
      // 填充透明度
      fillOpacity: 0.4,
      path: [],
      map: undefined,
      polygon: undefined,
      // 地图右键菜单
      contextMenu: undefined,
      // 地图点击事件监听
      clickListener: undefined,
      // 输入提示组件id
      autoOptions: {
        input: 'tipinput'
      },
      // 地图输入提示插件
      mapAutoComplete: undefined,
      // 地图输入提示点击监听
      autoCompleteSelectListener: undefined,
      // 地图地点查询类
      placeSearch: undefined,
      // 圆点标识，用于显示网格区域顶点
      circleMarker: [],
      // 所有网格员
      allGridAdmins: [],
      openTransfer: false,
      transferValue: [],
      transferTmp: [],
      transferCancelOperation: true,
      mapSearch: {
        key: '',
        city: ''
      },
      openGridAdmin: false,
      selectedGridNo: '',
      selectedGridName: '',
      showPolyEditor: false,
      gridLeaderLoading: false,
      gridLeaderOptions: [],
      tenantDistrictInfo: undefined,

      // 表单参数
      form: {
        id: undefined,
        province: undefined,
        city: undefined,
        district: undefined,
        street: undefined,
        committee: undefined,
        gridCode: undefined,
        gridName: undefined,
        createTime: undefined,
        updateTime: undefined,
        gridLevel: undefined,
        gridType: '1',
        gridScope: undefined,
        gridAdminShow: '',
        gridAdmin: []
      },
      isedit: false,
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    /** 二维数组转字符串 **/
    doubleDiaArray2Str (array) {
      let arrLen = array.length
      let row = '['
      for (let i = 0; i < arrLen; i++) {
        row += '['
        for (let j = 0; j < array[i].length; j++) {
          row += array[i][j]
          if (j < array[i].length - 1) {
            row += ','
          }
        }
        row += ']'
        if (i < arrLen - 1) {
          row += ','
        }
      }
      row += ']'
      return row
    },
    /** 字符串转二维数组 **/
    str2DoubleDiaArray (str) {
      if (str != undefined && str != null && str.length > 0) {
        return eval(str)
      }
    },
    mapClickCallback (e) {
      if(this.isedit){
        return
      }
      const coordinate = [e.lnglat.lng, e.lnglat.lat]
      this.path.push(coordinate)
      let pathTmp = []
      Object.assign(pathTmp, this.path)
      // 新增顶点
      this.addCircleMarker(e.lnglat.lng, e.lnglat.lat)
      this.addPolygon(pathTmp)
      //this.pointstr = this.doubleDiaArray2Str(this.path)

      this.$emit("update:pointstr",this.doubleDiaArray2Str(this.path))
    },
    /** 初始化map **/
    initMap () {
      // if (!this.map) {
      this.map = new AMap.Map('grid-map-container', {
        resizeEnable: true, //是否监控地图容器尺寸变化
        zoom: this.zoom, //初始化地图层级
        center: [116.34703902, 40.48188] //初始化地图层级
      })
      // }
      let that = this
      // 地图加载完成的回调
      this.map.on('complete', function () {
        if (that.operationType != 1) {
          // 编辑和查看时需要调用的操作，加载网格范围
          that.loadGridScope()
        }
      })
      /*      if (this.clickListener) {
              // 先解除绑定，防止重复绑定
              AMap.event.removeListener(this.clickListener)
            }*/

      if (this.operationType != 3) {
        // 新增和编辑时才绑定鼠标点击事件
        this.clickListener = AMap.event.addListener(this.map, 'click', function (e) {
          that.mapClickCallback(e)
        })
      }
      this.initAutoCompletePlugin('蓟州')
      // 初始化之后必须把提示控件的z-index设置高一点，否则会被modal遮盖
      $('.amap-sug-result').attr('style', 'z-index:3000')
      if (!this.placeSearch) {
        // 构造地点查询类
        this.placeSearch = new AMap.PlaceSearch({
          pageSize: 1, // 单页显示结果条数
          pageIndex: 1 // 页码
        })
      }

    },
    polyEditorOpen () {
      this.polyEditor.open()
      this.isedit=true
      if (this.clickListener) {
        // 编辑区域时，先解除绑定，防止点击事件重复
        //AMap.event.removeListener(this.clickListener)
      }
    },
    polyEditorClose () {
      this.polyEditor.close()
      this.isedit=false
      // 结束编辑时重新绑定鼠标点击事件
      let that = this
      /*this.clickListener = AMap.event.addListener(this.map, 'click', function (e) {
        that.mapClickCallback(e)
      })*/
    },
    /** 初始化输入提示控件，默认查询范围是全国 **/
    initAutoCompletePlugin (city) {
      // 先移除已经创建的监听
      if (this.autoCompleteSelectListener) {
        AMap.event.removeListener(this.autoCompleteSelectListener)
      }
      // 初始化输入提示控件
      this.mapAutoComplete = new AMap.Autocomplete({
        city: city,
        input: 'tipinput'
      })
      // 注册监听，当选中某条记录时会触发
      this.autoCompleteSelectListener = AMap.event.addListener(this.mapAutoComplete, 'select', this.mapOptionSelect)
    },
    mapOptionSelect (e) {
      this.mapSearch.key = e.poi.name
      this.mapSearch.city = e.poi.adcode
      this.handleMapSearch()
    },
    handleMapSearch () {
      let that = this
      if (this.placeSearch) {
        this.placeSearch.setCity(this.mapSearch.city)
        this.placeSearch.search(this.mapSearch.key, function (status, result) {
          if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
            if (that.map) {
              let point = result.poiList.pois[0].location
              that.map.setCenter([point.lng, point.lat])
              that.map.setZoom(17)
            }
          } else {
            that.msgError('未找到相应地点:' + this.mapSearch.key)
          }
        })
      }
    },
    /** 创建右键菜单 **/
    initContextMenu () {
      this.contextMenu = new AMap.ContextMenu()
      let that = this
      this.contextMenu.addItem('清空选择区域', function () {
        // 清空选择区域
        if (that.map && that.polygon) {
          that.map.remove(that.polygon)
        }
        that.polygon = undefined
        //清空编辑器
        if (that.polyEditor) {
          that.polyEditorClose();
        }
        that.polyEditor = undefined
        that.path = []
        that.$emit("update:pointstr",'')
        // 清空区域端点
        that.clearCircleMarker()
        that.showPolyEditor = false;
      }, 0)
    },
    /** 在地图上加载网格范围 **/
    loadGridScope () {
      let that = this
      if (this.map && this.pointstr != undefined && this.pointstr.length > 0) {
        // 将网格区域显示在地图上
        this.path = this.str2DoubleDiaArray(this.pointstr)
        let pathTmp = []
        Object.assign(pathTmp, this.path)
        this.addPolygon(pathTmp)
        // 将地图中心移动到此处
        this.map.setCenter(this.path[0])
        // this.map.setZoom(15);
        this.map.setFitView([this.polygon])

        //编辑网格区域时，取消鼠标点击监听
        this.polygonEditorListener();
      }
    },

    //多边形编辑功能
    polygonEditorListener () {
      let that = this;
      if (this.operationType != 3) {
        this.showPolyEditor = true;
        this.polyEditor = new AMap.PolyEditor(this.map, this.polygon)

        this.polyEditor.on('addnode', function (event) {
          that.extractPolygonPath(event.target.w.path)
        })

        this.polyEditor.on('adjust', function (event) {
          that.extractPolygonPath(event.target.w.path)
        })

        this.polyEditor.on('removenode', function (event) {
          that.extractPolygonPath(event.target.w.path)
        })

        this.polyEditor.on('end', function (event) {
          // event.target 即为编辑后的多边形对象
          that.extractPolygonPath(event.target.w.path)
        })
      }
    },
    extractPolygonPath (pathArray) {
      let polygonPath = []
      pathArray.forEach(item => {
        let coordinate = [item.lng, item.lat]
        polygonPath.push(coordinate)
      })
      //this.pointstr = this.doubleDiaArray2Str(polygonPath)
      this.$emit("update:pointstr",this.doubleDiaArray2Str(polygonPath))
    },
    addCircleMarker (lng, lat) {
      let circle = new AMap.CircleMarker({
        center: [lng, lat],
        radius: 2, //半径
        borderWeight: 1,
        strokeColor: this.fillColor,
        strokeOpacity: 1,
        strokeWeight: 1,
        fillOpacity: 1,
        // 线样式还支持 'dashed'
        fillColor: this.fillColor,
        zIndex: 50
      })
      if (this.map) {
        circle.setMap(this.map)
      }
      this.circleMarker.push(circle)
    },
    clearCircleMarker () {
      if (this.map) {
        this.circleMarker.forEach(item => {
          this.map.remove(item)
        })
      }
      this.circleMarker = []
    },
    clearPolygon () {
      var that = this;
      // 清空选择区域
      if (that.map && that.polygon) {
        that.map.remove(that.polygon)
      }
      that.polygon = undefined
      //清空编辑器
      if (that.polyEditor) {
        that.polyEditorClose();
      }
      that.polyEditor = undefined
      that.path = []
      that.$emit("update:pointstr",'')
      // 清空区域端点
      that.clearCircleMarker()
      that.showPolyEditor = false;
    },
    addPolygon (path) {
      if (this.polygon) {
        this.map.remove(this.polygon)
        this.polyEditor = undefined;
      }
      let polygontmp = new AMap.Polygon({
        path: path,
        strokeColor: this.strokeColor,
        strokeWeight: this.strokeWeight,
        strokeOpacity: this.strokeOpacity,
        fillOpacity: this.fillOpacity,
        fillColor: this.fillColor
      })
      let that = this
      if (this.contextMenu && this.operationType != 3) {
        polygontmp.on('rightclick', function (e) {
          that.contextMenu.open(that.map, e.lnglat)
        })
      }
      this.polygon = polygontmp
      this.map.add(polygontmp)
      this.polygonEditorListener();
    },
    /** 地图定位缩放初始化 **/
    reLocation () {
      if (this.map && this.operationType == 1) {
        if (this.polygon) {
          this.map.setFitView([this.polygon])
        } else {
          this.map.setZoom(this.zoom)
        }
        this.map.setCenter(this.center)
      }
    },
    /** 穿梭框筛选名字 **/
    filterGridAdmin (query, item) {
      return item.label.indexOf(query) > -1;
    },
    transferOk () {
      this.openTransfer = false;
      this.transferCancelOperation = false;
      this.form.gridAdminShow = '';
      this.form.gridAdmin = [];
      if (this.transferValue.length > 0) {
        let userMap = this.formatUserListToUserMap(this.allGridAdmins);
        this.transferValue.forEach(item => {
          let tmp = {
            userId: item
          };
          this.form.gridAdmin.push(tmp);
          this.form.gridAdminShow = this.form.gridAdminShow + userMap[item].name + ";";
        })
      }
    },
    /** 把网格员数组转换成map数据结构，提高查询效率 **/
    formatUserListToUserMap (userList) {
      let userMap = {};
      if (userList.length > 0) {
        userList.forEach(item => {
          userMap[item.key] = item;
        })
      }
      return userMap;
    },
  }
}
</script>

<style scoped>
#grid-map-container {
  height: 500px;
}

.map-container {
}

.map-container .info {
  position: absolute;
  top: 0px;
  border-width: 0;
  opacity: 0.95;
}

.map-container .input-item {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.map-container .input-item-prepend {
  margin-right: -1px;
}

.map-container .input-item-text {
  width: auto;
  padding: 0.4rem 0.7rem;
  display: inline-block;
  text-align-last: justify;
  align-items: center;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  color: #495057;
  text-align: center;
  white-space: nowrap;
}

.map-container .tipinput {
  margin-top: 10px;
  margin-left: 10px;
  width: 350px;
}

.transfer-container {
  width: 762px;
  margin: 0 auto;
}
.form-item {
  width: 100%;
}

.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  width: 22rem;
  border-width: 0;
  border-radius: 0.5rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  top: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 0.75rem;
}
</style>
